/*
 * @Author: AI Generated
 * @Date: 2024-05-16
 * @Description: 留言模块服务
 */
import { Inject, Injectable } from '@nestjs/common';
import { CustomPrismaService, PrismaService } from 'nestjs-prisma';
import { ExtendedPrismaClient } from 'src/shared/prisma/prisma.extension';
import { ApiException } from 'src/common/exceptions/api.exception';
import { AddSysFeedbackDto, GetSysFeedbackListDto, UpdateSysFeedbackRemarkDto } from './dto/req-sys-feedback.dto';
import dayjs from 'dayjs';

@Injectable()
export class SysFeedbackService {
    constructor(
        private readonly prisma: PrismaService,
        @Inject('CustomPrisma')
        private readonly customPrisma: CustomPrismaService<ExtendedPrismaClient>,
    ) { }

    /* 分页查询留言列表 */
    async list(getSysFeedbackListDto: GetSysFeedbackListDto) {
        const { name, phoneNumber, status } = getSysFeedbackListDto;
        const { total, rows } = await this.customPrisma.client.sysFeedback.findAndCount({
            where: {
                name: {
                    contains: name,
                },
                phoneNumber: {
                    contains: phoneNumber,
                },
                ...(status === '1' ? {
                    remark: {
                        not: null
                    }
                } : status === '2' ? {
                    remark: null
                } : {})
            },
            orderBy: {
                createTime: 'desc',
            },
        });
        return { total, rows };
    }

    /* 通过id查询留言详情 */
    async getById(feedbackId: number) {
        const feedback = await this.prisma.sysFeedback.findUnique({
            where: {
                feedbackId,
            },
        });
        if (!feedback) throw new ApiException('该留言不存在');
        return feedback;
    }

    /* 添加留言 */
    async add(addSysFeedbackDto: AddSysFeedbackDto) {
        return await this.prisma.sysFeedback.create({
            data: addSysFeedbackDto,
        });
    }

    /* 更新备注 */
    async updateRemark(updateSysFeedbackRemarkDto: UpdateSysFeedbackRemarkDto) {
        const { feedbackId, remark } = updateSysFeedbackRemarkDto;
        return await this.prisma.$transaction(async (prisma) => {
            const feedback = await prisma.sysFeedback.findUnique({
                where: {
                    feedbackId,
                },
            });
            if (!feedback) throw new ApiException('该留言不存在，请重新查询后操作');

            return await prisma.sysFeedback.update({
                data: {
                    remark,
                    updateTime: dayjs().toISOString(),
                },
                where: {
                    feedbackId,
                },
            });
        });
    }
}